package com.gitee.cirnochat.common.aop;

import com.gitee.cirnochat.common.annotation.AuthCheck;
import com.gitee.cirnochat.common.exception.BusinessException;
import com.gitee.cirnochat.common.model.enums.ErrorCode;
import com.gitee.cirnochat.common.utils.RequestUtils;
import com.gitee.cirnochat.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;


/**
 * 权限校验 AOP
 *
 * @author FlanChan
 */
@Aspect
@Component
@AllArgsConstructor
public class AuthInterceptor {

    private final HttpServletRequest request;
    private final UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 1. 读取 accessToken
        String accessToken = request.getHeader("Authorization");
        if (StringUtil.isBlank(accessToken)) {
            throw new BusinessException(ErrorCode.NOT_TOKEN_ERROR, "Token 为空");
        }

        // 2. 获取设备 ID
        String deviceId = RequestUtils.getDeviceId(request);
        if (deviceId == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "设备 ID 不能为空");
        }

        Long userId = userService.validateAndParseUserId(accessToken, deviceId);

        // 3. 保存 userId 到 request 供 controller 层使用
        request.setAttribute("user", userId);

        // 4. 放行
        return joinPoint.proceed();
    }
}

